layui.use(["table", "layer", "form"], function() {
	var table = layui.table;
	var $ = layui.jquery;
	var layer = layui.layer;
	var form = layui.form;
	$("#searchBtn").on("click", function() {
		table.render({
			elem: "#userTable",
			url: "/user/list",
			page: true,
			limit: 5,
			limits: [5, 10, 15, 20],
			where: { username: $("#searchUsername").val() },
			cols: [[
				{ title: '用户名', field: 'username', width: '15%', align: "center" },
				{ title: '姓名', field: 'name', width: '15%', align: "center" },
				{
					title: '性别', width: '15%', templet: function(d) {
						return d.gender === "1" ? "男" : "女";
					}, align: "center"
				},
				{ title: '年龄', field: 'age', width: '15%', align: "center" },
				{ title: '状态', field: 'status', width: '15%', align: "center" },
				{ title: '操作', width: '25%', align: "center", toolbar: "#operateTemplate" }
			]]
		});
		//数据表操作事件
		table.on('tool(userTable1)', function(obj) {
			//点击删除按钮事件
			if (obj.event == "del") {
				layer.confirm("你确定要删除该用户吗？", function() {
					$.post("/user/del?id=" + obj.data.id, function() {
						layer.closeAll();
						$("#searchBtn").click();
					});
				}, function() { });
			}
			//点击编辑按钮事件
			if (obj.event == "edit") {
				$.get("/user/" + obj.data.id, function(ret) {
					layer.open({
						type: 1,
						title: "编辑用户",
						content: $("#userFormTemplate").html(),
						area: ['500px', '400px']
					});
					form.val("userForm", ret);
				});
			}
			if (obj.event == "role") {//绑定角色
				$.get("/role/all?userId="+obj.data.id, function(ret) {
					layer.open({
						type: 1,
						title: "绑定角色",
						content: $("#userRoleTemplate").html(),
						area: ['500px', '400px']
					});
					//遍历所有角色放在form中展示
					$.each(ret, function(i, v) {
						$("#userRoleDiv").append("<input type='checkbox' "+ (v.checked?'checked':'') +" name='role["+v.id+"]' value='" + v.id + "' title='" + v.name + "' >");
					});
					form.render();
					
					//用户绑定角色的form中复选框事件绑定
					form.on('checkbox', function(data) {
						var value = data.value;//获取复选框的值
						var checked = data.elem.checked;//获取选中状态
						var userId = obj.data.id;//要更改的用户的ID
						$.post("/user/changeRole",{userId:userId,roleId:value,type:checked?'add':'remove'});
					});
				});
			}
		});
	}).click();
	//给新增按钮绑定点击事件
	$("#addBtn").on("click", function() {
		layer.open({
			type: 1,
			title: "新增用户",
			content: $("#userFormTemplate").html(),
			area: ['500px', '400px']
		});
		form.render();

	});
	//弹出窗口中保存按钮绑定事件
	$("body").on("click", "#saveBtn", function() {
		$.post("/user/save", form.val("userForm"), function() {
			layer.closeAll();
			$("#searchBtn").click();
		});
	});

	

});